package com.tqw.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.tqw.order.service.OrderService;
import com.tqw.order.vo.OrderPayInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: czm
 * @Date: 2022/04/20/14:53
 * @Description:支付接口
 */
@RestController
@RequestMapping("/order")
public class OrderPayController {
    private final String APP_ID = "2021000119671921";
    private final String APP_PRIVATE_KEY ="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCvKFuteLNPImNg2GkZsJkgkgL1OB/Uk5BI6rghcwL6Rzrwhpfz7XqnFVoqzj2fUYmxqNcqTfdfABPfdYuEOCJRqJXllpxb2yBM3zyODw6xwM9XnapG9x1ZBDhaGwm9lEFdHsxswahRylSMyUTNkHXiC46SkqHDEcysCPE/Dlh0Je0uLXv8Ya4lO28REdMO49FXtT8cVHLlb7Nl6lR1jep48Evur46rJVmVMdd/6Y+6RVpD8PQzRy1sPDLjEC8gb/C8O+Hxq+tT059ksZBhWYhRAb4DWg8FIlFtLbcUHht1pWMD2U/cOwaascsbByWqOzww0a9S5MNR2YHJeMhMd2RFAgMBAAECggEBAIGutcHH3ao3YbCwSZBVqentcPcxqI9w+aCi99T8HDZFSqQOYq6dIvRV4L5UmFc+vV2mDjgqJX5Wxl/p3XP1Q6OF2AV17yorIM0JcwISr+R3RowuFYYZK8deUoKUBjAwdfyF8wCKmR6FWPgrhB9WV5EW0WY/3jhZE1pD/Kmc62yB8bfwc5ODekgthfNvK4KN0Zqzj+IEaW5JrjRjlE+jy9n9/xi4qHxvJ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BCgKCAQEA3ShGR7YWavEaQXgTHYBLaVOru/OsGr5rITgzvwdpRLzWZ6piBQiQj03vg2B86i+uW8MvXkBdFrhw6Pya8SewfXttDIn5E+RiBnNV3KHXnlqqeOKjdkGexvkNNlCLq8zQV0H0UFaEfB+IR2E+7we0YvPYzlBDovhYE2g74wduFfZjGs+2w37lF/NxFxqcs1CjiEavaKV8BgX3ph+NnlsPM8v0ApSbBn6X6WV/Y78IEq/XjqF7DvN4QvJ+CVFGUUSPaCO7zaaHL3QKYHV6izCNRyQNyQMP1WvO7VpqUb2s5vaKFWyqYeHCIu2r0Tqg8cRc7it7hNOZ4kkKlgPN/1wCRwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址 订单状态修改
    private final String NOTIFY_URL = "http://tqwtqw.vaiwan.com/tqw/order/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址 页面返回
    private final String RETURN_URL = "http://web.tqw.com/#/paysuccess?";

    @Autowired
    private OrderService orderService;

    @PostMapping("/alipay")
    public void alipay(@RequestBody OrderPayInfoVO orderPayInfoVO, HttpServletResponse httpResponse) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);
        //根据订单编号,查询订单相关信息
        String orderId = orderPayInfoVO.getOrderId();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderId;
        //付款金额，必填
        String total_amount = orderPayInfoVO.getPrice().toString();
        System.out.println(total_amount);
        //订单名称，必填
        String subject = "淘弃屋";
        //商品描述，可空
        String body = "";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping(value ="/notifyUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("-------------进入异步回调--------------");
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE);
        //验证签名通过
        if (signVerified) {

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            //支付成功，更新订单状态
            orderService.updatePayOrder(out_trade_no);
        }
    }

}